---------------------------------------------------
-- 召唤法阵

-- drawCard = {jifen=0,list={[1]={},[2]={},[3]={},[4]={}}},--召唤法阵
-- drawInfo = {time,cntHero,cntHero2,chengjiuCnt,isRaward}
---------------------------------------------------

local ItemExcel = require("excel.item")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local Util = require("common.Util")
local Log = require("common.Log")
local Grid = require("bag.Grid")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local CommonDefine = require("common.CommonDefine")
local HeroDefine = require("hero.HeroDefine")
local ItemDefine = require("bag.ItemDefine")
local HeroLogic = require("hero.HeroLogic")
local BagLogic = require("bag.BagLogic")
local HeroGrid = require("hero.HeroGrid")
local DrawCardExcel = require("excel.drawCard").drawCard
local DrawCardActivityExcel = require("excel.drawCard").activity
local DailyTaskLogic = require("dailyTask.DailyTaskLogic")
local ChengjiuLogic = require("chengjiu.ChengjiuLogic")
local ChengjiuDefine = require("chengjiu.ChengjiuDefine")
local HeroExcel = require("excel.hero").hero
local MailExcel = require("excel.mail")
local MailManager = require("mail.MailManager")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
local MonthSummon = require("monthAct.MonthSummon")  
local HeroBook = require("hero.HeroBook")
local RoleDefine = require("role.RoleDefine")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local GuideLogic = require("guide.GuideLogic")
local RandomLogic = require("common.RandomLogic")
local TuiSongLiBao = require("present.TuiSongLiBao")
local MoshouLogic = require("moshou.MoshouLogic")
local LiLianLogic = require("dailyTask.LiLianLogic")
local ProjectLogic = require("platform.ProjectLogic")
local SysParameter = require("common.SysParameter")
local AbsActLogic = require("absAct.AbsActLogic")
local AbsActDefine = require("absAct.AbsActDefine")
local HeroUpLogic = require("absAct.HeroUpLogic")
local PerpleHeroLogic = require("absAct.PerpleHeroLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local PanelDefine = require("broadcast.PanelDefine")
local VipLogic = require("vip.VipLogic")
local MengxinLogic = require("present.MengxinLogic")
local LimitPerpleHeroLogic = require("present.LimitPerpleHeroLogic")
local HeroComeLogic = require("absAct.HeroComeLogic")
Json = Json or require("common.Json")

DRAWCARD_ID0 = 0	-- 积分召唤
DRAWCARD_ID1 = 1	-- 基础召唤
DRAWCARD_ID2 = 2	-- 高级召唤
DRAWCARD_ID3 = 3	-- 友情召唤
DRAWCARD_ID4 = 4	-- 积分召唤权重
DRAWCARD_ID5 = 5	-- 高级召唤十连抽必出
DRAWCARD_ID6 = 6	-- 高级召唤单抽
DRAWCARD_ID7 = 7    -- 40高抽必出SSR

DRAWCARD_OP_1 = 1	-- 召唤1次
DRAWCARD_OP_2 = 2	-- 召唤10次

DRAWCARD_JIFEN_NEED_VIPLV = 3
DRAWCARD_JIFEN_SHOW_ITEM = 801005

MAX_JIFEN = 3000

DRAWCARD_40 = 40    -- 40连抽，必得SSR

-- 积分
function getJifen(human)
    return human.db.drawCard.jifen 
end

function updateJifen(human, d)
   human.db.drawCard.jifen = human.db.drawCard.jifen or 0
   human.db.drawCard.jifen = human.db.drawCard.jifen + d
end

-- 根据抽奖id获取相关信息
function getDrawInfo(human, id)
    return human.db.drawCard.list[id]
end

-- 免费CD
function getFreeInfo(human, id)
    if id ~= DRAWCARD_ID1 and id ~= DRAWCARD_ID2 then
        return 0, 0 --只有普通和高抽可以免费 
    end

    local info = getDrawInfo(human, id)
    local config = DrawCardExcel[id]
    local leftCnt = 1
    local leftTime = 0
    if not info.time then 
        return leftCnt, leftTime
    end
    leftTime = math.max(info.time - os.time(), 0)
    if leftTime > 1 then
       leftCnt = 0
    end
    return leftCnt, leftTime
end

-- 设置免费冷却CD
function setUseFree(human, id)
    local info = getDrawInfo(human, id)
    if not info then return end  
    local config = DrawCardExcel[id]
    info.time = Util.getDayStartTime(os.time()) + 86400
end

-- 可否买免费
function isFree(human, id, op)
    if op ~= DRAWCARD_OP_1 then return end
    local leftCnt, leftTime = getFreeInfo(human, id)
    if leftCnt > 0 and leftTime < 1 then
        return true
    end
end

-- 10连次数
function getDraw2Cnt(human, id)
    local info = getDrawInfo(human, id)
    if not info then return 0 end
    return info.cntHero2 or 0
end

function addDraw2Cnt(human, id, cnt)
    local info = getDrawInfo(human, id)
    if not info then return end   
    info.cntHero2 = (info.cntHero2 or 0) + cnt
end

-- 单抽次数
function getDrawCnt(human, id)
    local info = getDrawInfo(human, id)
    if not info then return 0 end
    return info.cntHero or 0
end

function addDrawCnt(human, id, cnt)
    local info = getDrawInfo(human, id)
    if not info then return end   
    info.cntHero = (info.cntHero or 0) + cnt
end

function setSkip(human, id, skip)
    human.db.drawCard.skip = skip or 0
end

-- 连续1-4英雄次数
function getDrawNoGoodCnt(human, id)
    local info = getDrawInfo(human, id)
    if not info then return 0 end
    return info.chengjiuCnt or 0
end

function addDrawNoGoodCnt(human, id, cnt)
    local info = getDrawInfo(human, id)
    if not info then return end 

    info.chengjiuCnt = (info.chengjiuCnt or 0) + cnt
end

function getDrawNoSSRCnt(human, id)
    local info = getDrawInfo(human, id)
    if not info then return 0 end

    return info.leftSSRCnt or 0
end

function addDrawNoSSRCnt(human, id, cnt)
    local info = getDrawInfo(human, id, cnt)
    if not info then return end

    info.leftSSRCnt = (info.leftSSRCnt or 0) + cnt
end

function clearDrawNoSSRCnt(human, id)
    local info = getDrawInfo(human, id)
    if not info then return end

    info.leftSSRCnt = nil
end

function clearDrawNoGoodCnt(human, id)
    local info = getDrawInfo(human, id)
    if not info then return end 

    info.chengjiuCnt = nil
end

-- 友情点
function getFriendHeart(human)
    return human.db.friendHeart
end

function fontDrawCardNet(net, id, human)
    local config = DrawCardExcel[id]
    local leftCnt, leftTime = getFreeInfo(human, id)
    net.id = id
    net.leftFreeTime = leftTime
    net.leftFreeCnt = leftCnt
    net.items[0] = 0
    if config.item1[1] and config.item1[2] then
        net.items[0] = net.items[0] + 1
        Grid.makeItem(net.items[net.items[0]], config.item1[1], config.item1[2])
    end
    
    local vipArg = 100
    if id == DRAWCARD_ID2 then
        vipArg = VipLogic.getPowerArgs(human, VipLogic.VIP_POWER21)
    end

    if config.item2[1] and config.item2[2] then
       net.items[0] = net.items[0] + 1
       Grid.makeItem(net.items[net.items[0]], config.item2[1], math.floor(config.item2[2] * vipArg / 100 ) )
    end

    vipArg = 0
    if id == DRAWCARD_ID2 then
        vipArg = VipLogic.getPowerArgs(human, VipLogic.VIP_POWER22)
    end

    net.zuanshi[0] = 2
    net.zuanshi[1] = config.zuanshi1
    net.zuanshi[2] = config.zuanshi2 + vipArg
    net.isFirst = (getDraw2Cnt(human, id) < 1) and 1 or 0
    net.canBuy = ItemExcel.buy[config.item1[1]] and 1 or 0
end

-- 三个抽奖列表
function query(human)
    local msgRet = Msg.gc.GC_DRAWCARD_QUERY
    msgRet.jifen = getJifen(human)
    msgRet.left = getDrawNoSSRCnt(human, DRAWCARD_ID2)
    msgRet.leftNoSRRCnt = DRAWCARD_40 - getDrawNoSSRCnt(human, DRAWCARD_ID2)
    msgRet.list[0] = 0
    for id = DRAWCARD_ID1, DRAWCARD_ID3 do        
        msgRet.list[0] = msgRet.list[0] + 1
        local net = msgRet.list[msgRet.list[0]]
        fontDrawCardNet(net, id, human)
    end

    local needItemID = ItemDefine.ITEM_XIANZHI_BAOZHU_ID
    Grid.makeItem(msgRet.qiyuan, needItemID, 1)
    msgRet.skip = human.db.drawCard.skip or 0
    Msg.send(msgRet, human.fd)
end

-- 抽奖结果
function sendDrawOp(human, id, op, heroList, items, heroNewList, heroIndexList,isAct)
    local msgRet = Msg.gc.GC_DRAWCARD_OP
    msgRet.isAct = isAct or 0
    msgRet.leftNoSRRCnt = DRAWCARD_40 - getDrawNoSSRCnt(human, DRAWCARD_ID2)
    local dataNet = msgRet.data
    dataNet.jifen = getJifen(human)
    dataNet.id = id
    dataNet.op = op
    dataNet.heros[0] = heroList and #heroList or 0
    for i = 1, dataNet.heros[0] do
        local heroID = heroList[i]
        local isNew = heroNewList and heroNewList[i]
        local index = heroIndexList and heroIndexList[i]
        HeroGrid.makeHeroNice(dataNet.heros[i], heroID, nil, isNew, index)      
    end
    dataNet.items[0] = 0
    if items and type(items) == "table" then
        for itemID, itemCnt in pairs(items) do
            dataNet.items[0] = dataNet.items[0] + 1
            Grid.makeItem(dataNet.items[dataNet.items[0]], itemID, itemCnt)
        end
    end
    fontDrawCardNet(msgRet.drawData, id, human)
    Msg.send(msgRet, human.fd)
end

-- 积分召唤

local function jifenDraw(human, isAct)
    local config = DrawCardExcel[DRAWCARD_ID4]
    if not config then return end

    local db = human.db.drawCard
    if getJifen(human) < MAX_JIFEN then
        return Broadcast.sendErr(human, Lang.DRAWCARD_ERR_NOJIFEN)
    end

    if HeroLogic.getEmptyCnt(human) < 1 then
        return Broadcast.sendErr(human, Lang.HERO_BAG_FULL)
    end
    
    local heroID = randHeroID(human, DRAWCARD_ID4, DRAWCARD_OP_1, config)

    updateJifen(human, -MAX_JIFEN)    
    
    local heroConfig = HeroExcel[heroID]
	ChatPaoMaLogic.broadcast(human, ChatPaoMaLogic.PAOMA_TYPE_BROAD_TYPE4, heroConfig.grade, heroID)
    local isNew = not HeroBook.isGet(human, heroConfig.id, heroConfig.star)
    local heroIndex, fenjielist = HeroLogic.addHero(human, heroID,nil, 1, "draw_card")
    Log.write(Log.LOGID_OSS_DRAWCARD, human.db._id, human.db.account, human.db.name, human.db.lv, DRAWCARD_ID4, heroID, 0, 0, 0, db.jifen)
    sendDrawOp(human, DRAWCARD_ID4, 0, {heroID}, fenjielist, {isNew}, {heroIndex}, isAct)
end

-- 检查道具+扣道具
function checkUseItem(human, id, op, config,isAct)
    local item = config["item" .. op]
    local zuanshi = config["zuanshi" .. op]
    if not item or not zuanshi then return end

    local itemID = item[1]
    local itemCnt = item[2]

    if id == DRAWCARD_ID2 and op == DRAWCARD_OP_2 then
        local vipArg = 100
        vipArg = VipLogic.getPowerArgs(human, VipLogic.VIP_POWER21)
        print(" checkUseItem  vipArg   ", vipArg, "  ,   old  :  " ,itemCnt , "  ,  new : ", math.floor(itemCnt * vipArg / 100 ) )
        itemCnt = math.floor(itemCnt * vipArg / 100 )
    end 
    print("  checkUseItem   itemID  itemCnt ", itemID, itemCnt)
    -- 活动只扣道具
    if isAct == AbsActDefine.ABS_ACT_TYPE_4 then
        local state,id = AbsActLogic.isStartedByType(human, AbsActDefine.ABS_ACT_TYPE_4)
        if not state then
            return
        end 
        local config = PerpleHeroLogic.getConfigByActID(id)
        itemID = config["item" .. op][1]
        itemCnt = config["item" .. op][2]
        if BagLogic.getItemCnt(human, itemID) >= itemCnt then -- 扣道具
            BagLogic.delItem(human, itemID, itemCnt, "draw_card")
            return true
        else
            return
        end
    elseif isAct == AbsActDefine.ABS_ACT_TYPE_19 then
        local state,id = AbsActLogic.isStartedByType(human, AbsActDefine.ABS_ACT_TYPE_19)
        if not state then
            return
        end 
        local config = HeroComeLogic.getConfigByActID(id)
        itemID = config["item" .. op][1]
        itemCnt = config["item" .. op][2]
        if BagLogic.getItemCnt(human, itemID) >= itemCnt then -- 扣道具
            BagLogic.delItem(human, itemID, itemCnt, "draw_card")
            return true
        else
            return
        end
    elseif isAct == AbsActDefine.OA_ACT_TYPE_501 then
        local limitState = LimitPerpleHeroLogic.checkOpen()
        if not limitState then
            return 
        end
        local config = LimitPerpleHeroLogic.getConfigByActID()
        itemID = config["item" .. op][1]
        itemCnt = config["item" .. op][2]
        if BagLogic.getItemCnt(human, itemID) >= itemCnt then -- 扣道具
            BagLogic.delItem(human, itemID, itemCnt, "draw_card")
            return true
        else
            return
        end
    end

    if isFree(human, id, op) then -- 免费
        setUseFree(human, id)
        return true
    elseif BagLogic.getItemCnt(human, itemID) >= itemCnt then -- 扣道具
        BagLogic.delItem(human, itemID,  itemCnt, "draw_card")
        return true
    elseif zuanshi > 0 then -- 扣钻石
        -- 抵扣道具
        local haveCnt = BagLogic.getItemCnt(human, itemID)

        local vipArg = 0
        if id == DRAWCARD_ID2 and op == DRAWCARD_OP_2 then
            vipArg = VipLogic.getPowerArgs(human, VipLogic.VIP_POWER22)
        end
        zuanshi = zuanshi + vipArg
        if haveCnt > 0 then          
            zuanshi = zuanshi - math.floor(zuanshi * haveCnt / itemCnt) 
            zuanshi = zuanshi > 0 and zuanshi or 0
        end       

        if not ObjHuman.checkRMB(human, zuanshi) then
           return 
        end

        if haveCnt > 0 then
           BagLogic.delItem(human, itemID, haveCnt, "draw_card")
        end
        ObjHuman.decZuanshi(human, -zuanshi, "draw_card")
        return true
    end

    if zuanshi <= 0 then
        Broadcast.sendErr(human, Util.format(Lang.DRAWCARD_ERR_NOITEM, ItemDefine.getValue(itemID, "name")))   
    end
end

-- 
function randHeroID(human, id, op, config, actConfig, randomIndex, isAct)
    if isAct == 0 then
        if id == DRAWCARD_ID1 and op == DRAWCARD_OP_1 and getDrawCnt(human, id) == 0 then
            -- 首次普通单抽
            return SysParameter.getSysParameter(SysParameter.PARAMETER_6)
        elseif id == DRAWCARD_ID2 and op == DRAWCARD_OP_1 and getDrawCnt(human, id) == 0 then
            return SysParameter.getSysParameter(SysParameter.PARAMETER_7)
        end
    end
    
    if randomIndex and isAct == 0 then
        if id == DRAWCARD_ID2 and op == DRAWCARD_OP_2 then
           local sysHeroList = nil
           local draw2Cnt = getDraw2Cnt(human, id)
           draw2Cnt = math.floor(draw2Cnt/10)
           if draw2Cnt == 0 then
              sysHeroList = SysParameter.getSysParameterTb(SysParameter.PARAMETER_11)
           elseif draw2Cnt == 1 then
              sysHeroList = SysParameter.getSysParameterTb(SysParameter.PARAMETER_12)
           elseif draw2Cnt == 2 then
              sysHeroList = SysParameter.getSysParameterTb(SysParameter.PARAMETER_13)
           end

           if sysHeroList then
              local totoalWeight = 0
              for i=1, #sysHeroList do
                 totoalWeight = totoalWeight + sysHeroList[i][2]
              end
             
              local r = math.random(1, totoalWeight)
              for i=1, #sysHeroList do 
                 if r <= sysHeroList[i][2] then
                    return sysHeroList[i][1]
                 end
                 r = r - sysHeroList[i][2]
              end
           end
        end
    end

    local heroID = nil
    local rindex = RandomLogic.getRandom1(config.weight, nil, 2)
    local rconf = config.weight[rindex]
    local weightLv = rconf[1]
    if weightLv >= 8 and actConfig then
        local rindex2 = RandomLogic.getRandom3(actConfig)
        local rconf2 = rindex2 and actConfig[rindex2]
        if rconf2 then
            return rconf2.heroID
        end
    end

    heroID = heroID or HeroDefine.getRandHeroByWeightLv(weightLv)
    local actHeroID = AbsActLogic.getLuckDraw(human,luckDraw,randomIndex,isAct,op)
    if actHeroID then
        heroID = actHeroID
    end
    return heroID
end

-- 基础，高级，友情召唤，活动召唤
local function draw(human, id, op, actConfig, skip,isAct)
    if isAct == AbsActDefine.ABS_ACT_TYPE_4 then
        PerpleHeroLogic.onDrawCardActive(human, id, op, actConfig, skip,isAct)
        return
    elseif isAct == AbsActDefine.OA_ACT_TYPE_501 then
        LimitPerpleHeroLogic.onDrawCardActive(human, id, op, actConfig, skip,isAct)
        return
    elseif isAct == AbsActDefine.ABS_ACT_TYPE_19 then
        HeroComeLogic.onDrawCardActive(human, id, op, actConfig, skip,isAct)
        return
    end

    local config = DrawCardExcel[id]
    if not config then return end

    local heroCnt = nil
    if op == DRAWCARD_OP_1 then
        heroCnt = 1
    elseif op == DRAWCARD_OP_2 then
        heroCnt = 10
    else
        return
    end

    if HeroLogic.getEmptyCnt(human) < heroCnt then
        return Broadcast.sendErr(human, Lang.HERO_BAG_FULL)
    end

    if not checkUseItem(human, id, op, config,isAct) then
        return
    end

    setSkip(human, id, skip)

    local heroLen = 0
    local heroList = {}
    local heroNewList = {}
    local heroIndexList = {}
    local fenjielist = {}
    local heroIDs = nil

    local randomMin = math.random(1, heroCnt)
    for i = 1, heroCnt do
        config = DrawCardExcel[id]
        if id == DRAWCARD_ID2 and op == DRAWCARD_OP_2 and i == randomMin and getDraw2Cnt(human, id) > 3 then
            config = DrawCardExcel[DRAWCARD_ID5]
        elseif id == DRAWCARD_ID2 and op == DRAWCARD_OP_1 then
            config = DrawCardExcel[DRAWCARD_ID6]
        end

        -- 第40抽必出SSR
        if id == DRAWCARD_ID2 and getDrawNoSSRCnt(human, id) >= DRAWCARD_40 - 1 then
            config = DrawCardExcel[DRAWCARD_ID7]
        end

        local heroID = randHeroID(human, id, op, config, actConfig, i == randomMin, isAct)
        local heroConfig = HeroExcel[heroID]
        local star = heroConfig.star
		local name = heroConfig.name
        local grade = heroConfig.grade
        local isNew = not HeroBook.isGet(human, heroConfig.id, heroConfig.star)
        local heroIndex, fjlist = HeroLogic.addHero(human, heroID,nil, 1, "draw_card")
        heroLen = heroLen + 1
        heroList[heroLen] = heroID
        heroNewList[heroLen] = isNew
        heroIndexList[heroLen] = heroIndex
        if fjlist and type(fjlist) == "table" then
            for fjItemID, fjItemCnt in pairs(fjlist) do
                fenjielist[fjItemID] = (fenjielist[fjItemID] or 0) + fjItemCnt
            end
        end
        if not heroIDs then
            heroIDs = heroID
        else
            heroIDs = heroIDs .. "|" .. heroID
        end

        -- 判断召唤出来的英雄是否为ssr
        if grade < 4 then
            addDrawNoSSRCnt(human, id, 1)
        else
            clearDrawNoSSRCnt(human, id)
        end

        if star < 5 then
            addDrawNoGoodCnt(human, id, 1)
        else
            clearDrawNoGoodCnt(human, id)
        end

        if getDrawCnt(human, id) > 0 or getDraw2Cnt(human, id) > 0 then
            if id == DRAWCARD_ID1 then
                ChatPaoMaLogic.broadcast(human, ChatPaoMaLogic.PAOMA_TYPE_BROAD_TYPE3, grade, heroID)
            elseif id == DRAWCARD_ID2 then
                ChatPaoMaLogic.broadcast(human, ChatPaoMaLogic.PAOMA_TYPE_BROAD_TYPE1, grade, heroID)
            elseif id == DRAWCARD_ID3 then
                ChatPaoMaLogic.broadcast(human, ChatPaoMaLogic.PAOMA_TYPE_BROAD_TYPE2, grade, heroID)
            elseif id == DRAWCARD_ID6 then
                ChatPaoMaLogic.broadcast(human, ChatPaoMaLogic.PAOMA_TYPE_BROAD_TYPE21, grade, heroID)
            end
        end

        if op == DRAWCARD_OP_1 then
            addDrawCnt(human, id, 1)
        elseif op == DRAWCARD_OP_2 then
            addDraw2Cnt(human, id, 1)
        end

        if id == DRAWCARD_ID1 then
            LiLianLogic.onCallback(human,LiLianLogic.LILIAN_OUTID26,1,star)
        elseif id == DRAWCARD_ID2 then
            LiLianLogic.onCallback(human,LiLianLogic.LILIAN_OUTID27,1,star)
        end
    end

    updateJifen(human, config.jifen * heroCnt)
    if id == DRAWCARD_ID2 then
        ChengjiuLogic.onCallback(human,ChengjiuDefine.CJ_TASK_TYPE_2,heroCnt)
        MengxinLogic.onCallBack(human,MengxinLogic.MX_TASK_TYPE_12,heroCnt)
        YunYingLogic.onCallBack(human, "onDrawCard", heroCnt, id)
    end

    sendDrawOp(human, id, op, heroList, fenjielist, heroNewList,heroIndexList,isAct)
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_401)
    Log.write(Log.LOGID_OSS_DRAWCARD, human.db._id, human.db.account, human.db.name, human.db.lv, id, heroIDs, itemID or 0, cnt or 0, zuanshi or 0, getJifen(human))

    DailyTaskLogic.recordDailyTaskFinishCnt(human, DailyTaskLogic.DAILY_TASK_ID_3, heroCnt)

    GuideLogic.setDoSpecialGuide(human, GuideLogic.SKIPTYPE_JUMP_DRAW)
end

function op(human, id, op, skip,isAct)
    if id == DRAWCARD_ID0 then
        jifenDraw(human, isAct)
        return
    end  

    if id == DRAWCARD_ID1 or id == DRAWCARD_ID2 or id == DRAWCARD_ID3 or id == DRAWCARD_ID6 then
        draw(human, id, op, nil, skip,isAct)
        return
    end
end

function initAfterHot()
    for _, config in pairs(DrawCardExcel) do
        local totalWeight = 0
        for k, v in ipairs(config.weight) do
            totalWeight = totalWeight + v[2]
        end
        config.totalWeight = totalWeight
    end
end

function isDot(human)
    if human.db.lv < 9 then
       return false
    end

    if isFree(human, DRAWCARD_ID1, DRAWCARD_OP_1) then
		return true
	end	
    if isFree(human, DRAWCARD_ID2, DRAWCARD_OP_1) then
		return true
	end	
    if BagLogic.getItemCnt(human, ItemDefine.ITEM_DRAWCARD_GAOCHOU_ID) >= 10 then
        return true
    end
    return false
end
